package com.hoan.client;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hoan.service.Book;
import com.hoan.service.IBookManager;

import java.util.List;
import java.util.logging.Logger;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class BookActivity extends AppCompatActivity {
    private static final String TAG = "BookActivity";

    private IBookManager bookController;
    private boolean connected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);
        ButterKnife.bind(this);

        Intent intent = new Intent();
        intent.setPackage("com.hoan.service");
        intent.setAction("com.hoan.service.BookService");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bookController = IBookManager.Stub.asInterface(service);
            connected = true;
            Log.i(TAG, "onServiceConnected：connected " + connected);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected：connected " + connected);
            bookController = null;
            connected = false;
        }
    };


    @OnClick({R.id.bt_list, R.id.bt_add, R.id.bt_size, R.id.bt_first})
    public void onViewClicked(View view) {
        boolean isExit = isServiceExist("com.hoan.service","com.hoan.service.BookService");
        Log.i(TAG, "onViewClicked：isExit " + isExit);

        if (!connected) {
            Toast.makeText(BookActivity.this, "远程服务已断开连接", Toast.LENGTH_SHORT).show();
            return;
        }

        switch (view.getId()) {
            case R.id.bt_list:
                try {
                    List<Book> bookList = bookController.getBookList();
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < bookList.size(); i++) {
                        sb.append(bookList.get(i).getName()).append(",");
                    }
                    Log.i(TAG, "所有书名：" + sb.toString());
                    Toast.makeText(BookActivity.this, "所有书名" + sb.toString(), Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_add:
                Book book = new Book("新书");
                try {
                    bookController.addBook(book);
                    Log.i(TAG, "向服务器添加了一本新书：" + book.getName());
                    Toast.makeText(BookActivity.this, "向服务器添加了一本新书：" + book.getName(), Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_size:
                try {
                    int size = 0;
                    size = bookController.getInt();
                    Log.i(TAG, "共有" + size + "本书");
                    Toast.makeText(BookActivity.this, "共有" + size + "本书", Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_first:
                try {
                    String name = bookController.getString();
                    Log.i(TAG, "第一本书的书名是：" + name);
                    Toast.makeText(BookActivity.this, "第一本书的书名是：" + name, Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connected) {
            unbindService(serviceConnection);
        }
    }

    public boolean isServiceExist(final String pkgName, final String action) {
        if (TextUtils.isEmpty(pkgName) || TextUtils.isEmpty(action)) {
            return false;
        }

        Intent intent = new Intent();
        intent.setPackage(pkgName);
        intent.setAction(action);
        PackageManager pm = getPackageManager();
        try {
            ResolveInfo resolveInfo = pm.resolveService(intent, 0);
            Log.i(TAG, "isServiceExist: resolveInfo=" + resolveInfo);
            return resolveInfo != null;
        } catch (Exception e) {
            Log.e(TAG, "isServiceExist: Exception->", e);
            return false;
        }
    }


}